﻿using System;

namespace ModbusTcp
{
    public static class ModbusPacketParser
    {
        public static void Parse(byte[] packet)
        {
            if (packet.Length < 8)
            {
                Console.WriteLine("Invalid Modbus packet length.");
                return;
            }

            // Parse Modbus TCP header
            var transactionId = BitConverter.ToUInt16(packet, 0);
            var protocolId = BitConverter.ToUInt16(packet, 2);
            var length = BitConverter.ToUInt16(packet, 4);
            var unitId = packet[6];
            var functionCode = packet[7];

            Console.WriteLine($"Transaction ID: {transactionId}");
            Console.WriteLine($"Protocol ID: {protocolId}");
            Console.WriteLine($"Length: {length}");
            Console.WriteLine($"Unit ID: {unitId}");
            Console.WriteLine($"Function Code: {functionCode}");

            // Process function code
            switch (functionCode)
            {
                case 1: // Read Coils
                case 2: // Read Discrete Inputs
                case 3: // Read Holding Registers
                case 4: // Read Input Registers
                    ParseReadResponse(packet);
                    break;
                default:
                    Console.WriteLine($"Unknown Function Code: {functionCode}");
                    break;
            }
        }

        private static void ParseReadResponse(byte[] packet)
        {
            if (packet.Length < 9)
            {
                Console.WriteLine("Invalid read response packet.");
                return;
            }

            var byteCount = packet[8];
            Console.WriteLine($"Data Byte Count: {byteCount}");

            var data = new byte[byteCount];
            Array.Copy(packet, 9, data, 0, byteCount);

            Console.WriteLine($"Data: {BitConverter.ToString(data)}");
        }
    }
}
